package com.duobab.springbootjpamysqldemo.service;

import com.duobab.springbootjpamysqldemo.controller.param.WebSiteParam;
import com.duobab.springbootjpamysqldemo.controller.result.WebSiteResult;
import com.duobab.springbootjpamysqldemo.dao.WebSiteRepository;
import com.duobab.springbootjpamysqldemo.domain.WebSite;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class WebSiteServiceImpl {
    @Autowired
    private WebSiteRepository webSiteRepository;

    public void addWebSite(WebSiteParam webSiteParam) {
        if (Objects.isNull(webSiteParam) || Objects.isNull(webSiteParam.getUrl())) {
            return;
        }
        WebSite webSite = new WebSite();
        webSite.setUrl(webSiteParam.getUrl());
        webSiteRepository.save(webSite);
    }

    public void delWebSite(Long id) {
        if (Objects.isNull(id)) {
            return;
        }
        webSiteRepository.deleteById(id);
    }

    public List<WebSiteResult> getWebSite() {
        List<WebSiteResult> results = new ArrayList<>();

        List<WebSite> webSiteList = webSiteRepository.findAll();
        webSiteList.forEach(webSite -> {
            WebSiteResult webSiteResult = new WebSiteResult();
            BeanUtils.copyProperties(webSite, webSiteResult);
            results.add(webSiteResult);
        });

        return results;
    }
}
